﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CRM.DataAccess.Entities;
using CRM.Business.Services;
using CRM.Encryption;
using Telerik.Web.UI;
using System.IO;

namespace Web.Product
{
    public partial class AddNewProduct : System.Web.UI.Page
    {
        static long? assignedToID = null; 
        static string prevPage = String.Empty;
        static PRODUCT product = new PRODUCT();
        static USER user;
        static ROLE r;
        static string defaultImage = "~/ProductImages/no_image_for_this_product.gif";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
                return;
            assignedToID = null; 
            if (Request.UrlReferrer != null)
            {
                prevPage = Request.UrlReferrer.ToString();
                hdntxtPrevPage.Value = prevPage;
            }

            user = (USER)Session["User"];
            if (user != null)
            {
                r = RoleService.GetRoleByID((long)user.ROLE_ID);
                if ((!(bool)user.IS_ADMIN) && (!(bool)r.IS_MANAGER))
                {
                    assignedToID = user.ID;
                    divAssignedTo.Visible = false;
                }
                txtWebsite.Attributes.Add("onblur", "CheckNull();");
                dpSalesStartDate.SelectedDate = DateTime.Now;
                dpSalesEndDate.SelectedDate = DateTime.Now.AddDays(7);
                dpSupportStartDate.SelectedDate = DateTime.Now;
                dpSupportExpiryDate.SelectedDate = DateTime.Now.AddDays(30);
                LoadAllUser();
                LoadUsageUnit();
                LoadSupplier();
                
                imgprw.Src = defaultImage;
            }
        }
        private void LoadAllUser()
        {
            ddlAssignedTo.Items.Clear();
            List<USER> users = UserService.ListAll();
            if (users != null)
            {
                foreach (USER u in users)
                {
                    ddlAssignedTo.Items.Add(new RadComboBoxItem(u.SUR_NAME + " " + u.NAME, u.ID.ToString()));
                }
            }
        }
        private void LoadUsageUnit()
        {
            ddlUsageUnit.DataSource = ProductService.GetProductUsageUnit();
            ddlUsageUnit.DataBind();
            ddlUsageUnit.Items.Insert(0, new RadComboBoxItem("Select an option", "-1"));
        }
        private void LoadSupplier()
        {
            ddlSupplier.DataSource = ProductService.GetProductManufacturer();
            ddlSupplier.DataBind();
            ddlSupplier.Items.Insert(0, new RadComboBoxItem("Select an option", "-1"));
        }

        private int addNewProduct()
        {

            //General information
            DateTime dt = DateTime.Now;
            product.DATE_ENTERED = dt;
            product.DATE_MODIFIED = dt;
            //Product detail
            product.PRODUCT_NAME = txtProductName.Text.Trim();
            product.PRODUCT_ACTIVE = chbProductActive.Checked;
            product.SERIAL_NO = txtSerialNo.Text.Trim();
            product.SALES_START_DATE = dpSalesStartDate.SelectedDate;
            if (ddlSupplier.SelectedValue != "-1")
                product.MANUFACTURER_ID = Convert.ToInt64(ddlSupplier.SelectedValue);
            product.PRODUCT_CATEGORY = txtProductCategory.Text.Trim();
            product.SUPPORT_START_DATE = dpSupportStartDate.SelectedDate;
            product.SALES_END_DATE = dpSalesEndDate.SelectedDate;
            product.SUPPORT_EXPIRY_DATE = dpSupportExpiryDate.SelectedDate;
            //product.VENDOR_ID = 1;//fix later
            product.WEBSITE = txtWebsite.Text.Trim();
            //Pricing Information
            product.UNIT_PRICE = rntxtUnitprice.Value;
            product.COMMISSION_RATE = rntxtCommissionRate.Value;
            product.GST_PERCENT = 0;
            if (chbGST.Checked)
                product.GST_PERCENT = rntxtGST.Value;
            if (chbSales.Checked)
                product.SALES_PERCENT = rntxtSales.Value;
            if (chbService.Checked)
                product.SERVICE_PERCENT = rntxtService.Value;

            //Stock Information
            if (ddlUsageUnit.SelectedValue != "-1")
                product.USAGE_UNIT_ID = Convert.ToInt64(ddlUsageUnit.SelectedValue);
            product.QTY_OUT_STOCK = 0;
            product.QTY_IN_STOCK = rntxtQuantity.Value;
            product.BALANCE = rntxtQuantity.Value;
            product.REORDER_LEVEL = rntxtReorderLevel.Value;
            
            if ((!(bool)user.IS_ADMIN) && (!(bool)r.IS_MANAGER))
                product.ASSIGN_TO = user.ID;
            else
            {
                if (ddlAssignedTo.SelectedItem == null)
                    product.ASSIGN_TO = null;
                else
                    product.ASSIGN_TO = Convert.ToInt64(ddlAssignedTo.SelectedValue);
            }

            product.QTY_IN_DEMAND = rntxtQtyInDemand.Value;
            //Description detail
            product.DESCRIPTION = txtDescription.Text.Trim();
            //Product image
            string img = product.IMAGE;
            if (AsyncUpload1.UploadedFiles.Count > 0)
            {
                string filename = "~/ProductImages/" + DateTime.Now.ToString("ddMMyyhhmmssttfff") + AsyncUpload1.UploadedFiles[0].GetExtension();
                AsyncUpload1.UploadedFiles[0].SaveAs(Server.MapPath(filename));
                
                product.IMAGE = filename;
            }
            else
                product.IMAGE = defaultImage;
            return ProductService.AddNewProduct(product);
        }

        protected void btn_Save_Click(object sender, EventArgs e)
        {

            int newProductResult = addNewProduct();
            if (newProductResult == 1)
            {
                RadAjaxManager.GetCurrent(this).ResponseScripts.Add(@"ShowMessageAndRedirect('" + "Add new product successful !" + "','" + "Products.aspx" + "');");
                //MessageBox.Show(this.Page, Page.GetType(), "Add new product successful !", "Products.aspx");
            }
            else
                RadAjaxManager.GetCurrent(this).ResponseScripts.Add(@"ShowMessage('" + "Can not add new product !" + "');");
                //RadWindowManager1.RadAlert("Can not add new product !", 300, 150, "", null);
        }


        protected void RadAjaxManager1_AjaxRequest(object sender, Telerik.Web.UI.AjaxRequestEventArgs e)
        {
            //Bind the RadComboBod 
            LoadSupplier();
        }

        protected void btn_Cancel_Click(object sender, EventArgs e)
        {
            Response.Redirect(prevPage);
        }

        protected void DeleteImage_Click(object sender, EventArgs e)
        {
            imgprw.Src = defaultImage;
        }
    }
}